package org.clob4eclipse.wizards;


import org.clob4eclipse.Config;
import org.clob4eclipse.PluginData;
import org.clob4eclipse.PluginLogger;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.operation.*;
import java.lang.reflect.InvocationTargetException;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import java.io.*;

import org.eclipse.ui.*;
import org.eclipse.ui.ide.IDE;


public class OracleClobWizard extends Wizard implements INewWizard {
	private OracleClobWizardPage page;
	private ISelection selection;

	/**
	 * Constructor for OracleClobWizard.
	 */
	public OracleClobWizard() {
		super();
		setNeedsProgressMonitor(true);
		
	}
	
	/**
	 * Adding the page to the wizard.
	 */
	public void addPages() {
		super.getShell().setSize(600, 440);
		page = new OracleClobWizardPage(selection);
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' button is pressed in
	 * the wizard. We will create an operation and run it
	 * using wizard as execution context.
	 */
	public boolean performFinish() {
		final PluginData data = page.getPluginData();
		
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {				
					doFinish(data.getContainerName(), data, monitor);
				} catch (CoreException e) {
					PluginLogger.logError("core exception: ", e);
					throw new InvocationTargetException(e);
				} catch (Exception e) {
					PluginLogger.logError("exception: ", e);
				} finally {
					monitor.done();
				}
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			//PluginLogger.logError("InterruptedException: ", e);
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			PluginLogger.logError("InvocationTargetException: ", e);
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * The worker method. It will find the container, create the
	 * file if missing or just replace its contents, and open
	 * the editor on the newly created file.
	 * @throws Exception 
	 */

	private void doFinish(
		String containerName,
		PluginData data,
		IProgressMonitor monitor)
		throws Exception {
		
		Config config = new Config(data);
		String fileName = null;
		IFile file = null;
		
		/*
		 * Check if connection could be established - if not error dialog
		 * */
		
		// fetch content from DB
		ResultSet rs = null;
		InputStream stream = null;
		String query = "select "+data.getFileNameColumn()+", "+data.getClobColumnName()+" from "+data.getTableName()+"";
		
		monitor.beginTask("Creating files in project!", 2);
		try {
			rs = config.getStatement().executeQuery(query);
			while (rs.next()) {
				
				fileName = rs.getString(1);
				fileName = fileName.trim().toLowerCase();
				fileName = fileName+".html";
				
				Clob clob = rs.getClob(2);
				stream = clob.getAsciiStream();
				
				file = createFileInProject(monitor, fileName, stream, data);
			}
			
			monitor.worked(1);
	
			final IFile openFile = file;
			monitor.setTaskName("Opening file for editing...");
			getShell().getDisplay().asyncExec(new Runnable() {
				public void run() {
					IWorkbenchPage page =
						PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
					try {
						IDE.openEditor(page, openFile, true);
					} catch (PartInitException e) {
						//PluginLogger.logError("PartInitException: ", e);
					}
				}
			});
			monitor.worked(1);
		} catch (SQLException e) {
			PluginLogger.logError("SQLException: ", e);
		} finally {
			try {
				if (config.getStatement() != null) config.getStatement().close();	
				if (config.getConnection() != null)	config.getConnection().close();
			} catch (SQLException e) {
				PluginLogger.logError("Failed to close Connection: ", e);
			}
		}
	}
	
	private IFile createFileInProject(IProgressMonitor monitor, String fileName, InputStream stream, PluginData data) throws CoreException, IOException{
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		IResource resource = root.findMember(new Path(data.getContainerName()));
		if (!resource.exists() || !(resource instanceof IContainer)) {
			throwCoreException("Container \"" + data.getContainerName() + "\" does not exist.");
		}
		IContainer container = (IContainer) resource;
		final IFile file = container.getFile(new Path(fileName));
		try {
			if (file.exists()) {
				file.setContents(stream, true, true, monitor);
			} else {
				file.create(stream, true, monitor);
			}
			stream.close();
		} catch (IOException e) {
			PluginLogger.logError("PartInitException: ", e);
			throw e;
		}
		return file;
	}

	private void throwCoreException(String message) throws CoreException {
		IStatus status =
			new Status(IStatus.ERROR, "OracleClobEditor", IStatus.OK, message, null);
		throw new CoreException(status);
	}

	/**
	 * We will accept the selection in the workbench to see if
	 * we can initialize from it.
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
}